<?php

namespace common\widgets;

use Yii;
use yii\helpers\Html;

/**
 * A Bootstrap 3 enhanced version of [[\yii\widgets\ActiveForm]].
 *
 * @see ActiveField for details on the [[fieldConfig]] options
 * @see http://getbootstrap.com/css/#forms
 *
 * @author Michael Härtl <haertl.mike@gmail.com>
 * @since 2.0
 */
class ActiveForm extends \yii\bootstrap\ActiveForm {

    /**
     * @var string the default field class name when calling [[field()]] to create a new field.
     * @see fieldConfig
     */
    public $fieldClass = '\common\widgets\ActiveField';

    /**
     * @var string the default field class name when calling [[field()]] to create a new field.
     * @see fieldConfig
     */
    public $actionButtonClass = 'btn btn-sm blue-hoki';

    /**
     * {@inheritdoc}
     * @return ActiveField the created ActiveField object
     */
    public function field($model, $attribute, $options = []) {
        return parent::field($model, $attribute, $options);
    }

    /**
     * 
     * @param Model $model
     * @param type $options
     * @return type
     */
    public function submit($model, $options = []) {
        $label = '保存内容';
        Html::addCssClass($options, $this->actionButtonClass);
        if ($model->isNewRecord) {
            $label = '提交信息';
        }
        return Html::submitButton($label, $options);
    }

    /**
     * Validates one or several models and returns an error message array indexed by the attribute IDs.
     * This is a helper method that simplifies the way of writing AJAX validation code.
     *
     * For example, you may use the following code in a controller action to respond
     * to an AJAX validation request:
     *
     * ```php
     * $model = new Post;
     * $model->load(Yii::$app->request->post());
     * if (Yii::$app->request->isAjax) {
     *     Yii::$app->response->format = Response::FORMAT_JSON;
     *     return ActiveForm::validate($model);
     * }
     * @return array the error message array indexed by the attribute IDs.
     */
    public static function validate($model, $attributes = null) {
        $result = [];
        if ($attributes instanceof \yii\base\Model) {
            // validating multiple models
            $models = func_get_args();
            $attributes = null;
        } else {
            $models = [$model];
        }
        /* @var $model Model */
        foreach ($models as $model) {
            $model->validate($attributes);
            foreach ($model->getErrors() as $attribute => $errors) {
                $result[\common\helpers\Html::getInputId($model, $attribute)] = $errors;
            }
        }
        return $result;
    }

}
